package com.coolingme.springframework.webmvc.servlet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.RandomAccessFile;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MeView {

    /**
     * 视图文件地址，D://XXX/layouts/viewName.html
     */
    private File viewFile;

    public MeView(File templateFile) {
        this.viewFile = templateFile;
    }

    public void render(Map<String, ?> model, HttpServletRequest req, HttpServletResponse resp) throws Exception {

        // 无反射，不框架
        // 无正则，不架构
        StringBuffer sb = new StringBuffer();
        // 读取视图对应的HTML文件
        RandomAccessFile ra = new RandomAccessFile(this.viewFile, "r");

        String line = null;
        while (null != (line = ra.readLine())) {
            line = new String(line.getBytes("iso-8859-1"), "utf-8");

            // 正则匹配￥{XXX}
            Pattern pattern = Pattern.compile("￥\\{[^\\}]+\\}", Pattern.CASE_INSENSITIVE);
            Matcher matcher = pattern.matcher(line);
            while (matcher.find()) {
                //  ￥{name}
                String paramName = matcher.group();

                // 获取传参值名，替换￥{name} -> name
                paramName = paramName.replaceAll("￥\\{|\\}", "");

                // 获取传参值
                Object paramValue = model.get(paramName);
                if (null == paramValue) {
                    continue;
                }

                // 将第一个命中的模板参数替换为传参，￥{teacher} -> XXX
                line = matcher.replaceFirst(makeStringForRegExp(paramValue.toString()));

                // 匹配下一行
                matcher = pattern.matcher(line);
            }
            // 替换值后在拼接
            sb.append(line);
        }

        // 设置返回值
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().write(sb.toString());
    }


    //处理特殊字符
    public static String makeStringForRegExp(String str) {
        return str.replace("\\", "\\\\").replace("*", "\\*")
                .replace("+", "\\+").replace("|", "\\|")
                .replace("{", "\\{").replace("}", "\\}")
                .replace("(", "\\(").replace(")", "\\)")
                .replace("^", "\\^").replace("$", "\\$")
                .replace("[", "\\[").replace("]", "\\]")
                .replace("?", "\\?").replace(",", "\\,")
                .replace(".", "\\.").replace("&", "\\&");
    }
}
